--create default fonts to use
surface.CreateFont("Tahoma", 16, 700, true, false, "MDCoretip18")
surface.CreateFont("Tahoma", 12, 400, true, false, "MDCoretip14")
surface.CreateFont("Tahoma", 20, 700, true, false, "MDCoretip22")

local WorldTip = nil

--Name: SetEntityTitle( )
--Desc: Sets the title of a entity on the client side
RS.SetEntTitle = function( entid, title )
	local ent = ents.GetByIndex(entid)

	if (!ent || !ent:IsValid()) then return end

	--save the title. TODO: find out why the timer is required to save title
	timer.Simple(0, function()
		ent.title = title
	end)
end

--save tip
function RS.AddWorldTip( self, settings )
	if !self then return end
	if !settings then settings = {} end

	WorldTip = {}
	WorldTip.ent 			= self
 	WorldTip.dietime 		= SysTime() + 0.05
 	WorldTip.position		= settings.position or "middle"
	WorldTip.boxColor 		= settings.boxColor or Color(0, 0, 0, 50)
	WorldTip.boxTextColor 	= settings.boxTextColor or Color(255,255,255,255)
	WorldTip.boxTextHeadColor 	= settings.boxTextHeadColor or Color(0,255,0,255)
	WorldTip.text1			= settings.text1 or "MDCoretip18"
	WorldTip.text2			= settings.text2 or "MDCoretip22"
end

--draws the tip on the screen
function RS.DrawWorldTip()
	local entPosition = nil
	local tip = WorldTip
	local ent = tip.ent

	if !ent || !ent:IsValid() || !RS.IsEnabled() then return end

	if tip.position == "bottom" then		--bottom
		entPosition = ent:OBBMins()
	elseif tip.position == "middle" then	--middle
		entPosition = ent:OBBCenter()
	else						--top
		entPosition = ent:OBBMaxs()
	end

	--get position to base hud off of
	local pos = ent:LocalToWorld(entPosition):ToScreen()

	--get text lines
	local tipText = string.Explode("\n", ent.title)

	--figure out box size based off normal text
	surface.SetFont( tip.text1 )
	local boxWidth, boxHeight = surface.GetTextSize( ent.title )

	--figure out box size based off header text
	surface.SetFont( tip.text2 )
	local boxWidth2, boxHeight2 = surface.GetTextSize( ent.title )
	if boxWidth2 > boxWidth then boxWidth = boxWidth2 end		--increae box width
	if boxHeight2 > boxHeight then boxHeight = boxHeight2 end	--increase box height

	boxWidth = boxWidth + 20
	boxHeight = boxHeight + 20 + (table.Count(tipText) * 2)

	--save box position
	local boxX = math.Clamp((pos.x - (boxWidth/2) - 50), 30, (ScrW()-boxWidth-30))
	local boxY = math.Clamp((pos.y - (boxHeight/2) - 50), 30, (ScrH()-boxHeight-30))

	--draw the box
	draw.RoundedBox(8, boxX, boxY, boxWidth, boxHeight, tip.boxColor)
	--do a border
	draw.RoundedBox(8, boxX - 10, boxY - 10, boxWidth + 20, boxHeight + 20, tip.boxColor)
	--do another border
	draw.RoundedBox(8, boxX - 12, boxY - 12, boxWidth + 24, boxHeight + 24, tip.boxColor)

	--set line starting point
	local nextLineX = boxY + 10

	--loop through the lines
	for i, text in pairs( tipText ) do
		local font, color = tip.text1, tip.boxTextColor	--set default font and color

		if (i == 1) then font, color = tip.text2, tip.boxTextHeadColor end	--set font and color to header

		local textLine = string.Explode("-", text)

		surface.SetFont( font )
		surface.SetTextColor( color )
		surface.SetTextPos( boxX + 10, nextLineX )
		surface.DrawText( textLine[1] )

		if textLine[2] then
			surface.SetFont( "MDCoretip14" )

			local numbers = string.Explode("/", textLine[2])

			if (numbers[1] && numbers[2]) then
				local low = numbers[1]
				local high = numbers[2]
				local percent = math.ceil((low/high) * 100)

				if (high == "0") then percent = 0 end

				local text = textLine[2]
				local fontWidth = surface.GetTextSize( text )
				surface.SetTextPos( boxX + boxWidth - fontWidth - 50, nextLineX )
				surface.DrawText( text )

				local text = "" .. percent .. "%"
				local fontWidth = surface.GetTextSize( text )
				surface.SetTextColor( Color(255, percent * 2.5, 0, 255) )
				surface.SetTextPos( boxX + boxWidth - fontWidth - 10, nextLineX )
				surface.DrawText( text )
			end
		end

		nextLineX = nextLineX + draw.GetFontHeight(font) + 3
	end
end

--draws the new world tip
function RS.HUDPaint()
	if ( WorldTip && WorldTip.dietime > SysTime() ) then
 		RS.DrawWorldTip()
 	end
end
--add hud hook to draw tips
hook.Add("HUDPaint", "RS.HudPaint", RS.HUDPaint)








local PANEL = {}

--[[---------------------------------------------------------
   Name: ControlValues
---------------------------------------------------------]]
function PANEL:AddModel( _, ConVars )
	-- Creeate a spawnicon and set the model
	local Icon = vgui.Create( "SpawnIcon", self )
	Icon:SetModel( ConVars.model )
	Icon:SetToolTip( ConVars.model )
	Icon.Model = ConVars.model
	Icon.ConVars = ConVars or {}

	local ConVarName = self:ConVar()

	-- Run a console command when the Icon is clicked
	Icon.DoClick =  function ( self )
		for name, value in pairs( self.ConVars ) do
			local cmd = Format( "%s \"%s\"\n", ConVarName .. "_" .. name, value )
			if (RS.Debug()) then MsgN(cmd) end
			LocalPlayer():ConCommand( cmd )
		end
	end

	-- Add the Icon us
	self.List:AddItem( Icon )
	table.insert( self.Controls, Icon )
end

--[[---------------------------------------------------------
   Name: ControlValues
---------------------------------------------------------]]
function PANEL:ControlValues( kv )
	self:SetConVar( kv.convar or "" )
	self.Label:SetText( kv.label or "#Untitled" )
	self.Height = kv.height or 2

	-- Load the list of models from our keyvalues file
	if (kv.models) then
		for k, v in pairs( kv.models ) do
			self:AddModel( k, v )
		end
	end

	self:InvalidateLayout( true )
end


local PANEL = {}

--[[---------------------------------------------------------
   Name: This function is used as the paint function for
		   selected buttons.
---------------------------------------------------------]]
local function HighlightedButtonPaint( self )
	surface.SetDrawColor( 255, 200, 0, 255 )

	for i=2, 3 do
		surface.DrawOutlinedRect( i, i, self:GetWide()-i*2, self:GetTall()-i*2 )
	end
end

--[[---------------------------------------------------------
   Name: Init
---------------------------------------------------------]]
function PANEL:Init()
	-- A panellist is a panel that you shove other panels
	-- into and it makes a nice organised frame.
	self.List = vgui.Create( "DPanelList", self )
		self.List:EnableHorizontal( true )
		self.List:EnableVerticalScrollbar()
		self.List:SetSpacing( 1 )
		self.List:SetPadding( 3 )

	self.Controls 	= {}
	self.Height		= 2
end

--[[---------------------------------------------------------
   Name: ControlValues
---------------------------------------------------------]]
function PANEL:AddModel( ConVars )
	local model = ConVars.model

	-- Creeate a spawnicon and set the model
	local Icon = vgui.Create( "SpawnIcon", self )
	Icon:SetModel( model )
	Icon:SetToolTip( model )
	Icon.Model = model
	Icon.ConVars = ConVars or {}

	local ConVarName = self:ConVar()

	-- Run a console command when the Icon is clicked
	Icon.DoClick = 	function ( self )
		for name, value in pairs( self.ConVars ) do
			local cmd = Format( "%s \"%s\"\n", ConVarName .. "_" .. name, value )
			if (RS.Debug()) then MsgN(cmd) end
			LocalPlayer():ConCommand( cmd )
		end
	end

	-- Add the Icon us
	self.List:AddItem( Icon )
	table.insert( self.Controls, Icon )
end

--[[---------------------------------------------------------
   Name: ControlValues
---------------------------------------------------------]]
function PANEL:ControlValues( kv )
	self.BaseClass.ControlValues( self, kv )
	self.Height = kv.height or 2

	-- Load the list of models from our keyvalues file
	if (kv.models) then
		for k, v in pairs( kv.models ) do
			self:AddModel( v )
		end
	end

	self:InvalidateLayout( true )
end

--[[---------------------------------------------------------
   Name: PerformLayout
---------------------------------------------------------]]
function PANEL:PerformLayout()
	local y = self.BaseClass.PerformLayout( self )
	local Height = 64 * self.Height + 7

	self.List:SetPos( 0, y )
	self.List:SetSize( self:GetWide(), Height )

	y = y + Height + 6

	self:SetTall( y )
end

--[[---------------------------------------------------------
   Name: SelectButton
---------------------------------------------------------]]
function PANEL:FindAndSelectButton( Value )
	self.CurrentValue = Value

	for k, Icon in pairs( self.Controls ) do
		if ( Icon.Model == Value ) then
			-- Remove the old overlay
			if ( self.SelectedIcon ) then
				self.SelectedIcon.PaintOver = nil
			end

			-- Add the overlay to this button
			Icon.PaintOver = HighlightedButtonPaint;
			self.SelectedIcon = Icon
		end
	end
end

--[[---------------------------------------------------------
   Name: TestForChanges
---------------------------------------------------------]]
function PANEL:TestForChanges()
	local Value = GetConVarString( self:ConVar() )

	if ( Value == self.CurrentValue ) then return end

	self:FindAndSelectButton( Value )
end

vgui.Register( "RSPropSelect", PANEL, "ContextBase" )